<template>
  <div class="alloc-menu">
    <el-card>
      <el-tree
        ref="menuTree"
        :data="data"
        show-checkbox
        node-key="id"
        :default-expand-all="true"
        :default-checked-keys="defaultCheckedKeys"
        :props="defaultProps">
      </el-tree>
      <div class="button-container">
        <el-button @click="reset">清空</el-button>
        <el-button type="primary" @click="onSubmit">保存</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
  import { allocateRoleMenus, getRoleMenus } from '@/services/menu'

  function findSelectedMenu(menuList, selectedItems) {
    for (const item of menuList) {
      if (item.selected && !item.subMenuList) {
        selectedItems.push(item.id)
      }
      if (item.subMenuList) {
        findSelectedMenu(item.subMenuList, selectedItems)
      }
    }
  }

  export default {
    name: 'AllocMenu',
    props: {
      roleId: {
        type: [String, Number],
        required: true,
      }
    },
    data() {
      return {
        data: [],
        defaultProps: {
          children: 'subMenuList',
          label: 'name'
        },
        defaultCheckedKeys: [],
      }
    },
    created() {
      this.loadMenuTree()
    },
    methods: {
      async loadMenuTree() {
        const { code, data } = await getRoleMenus(this.roleId)
        if (code === '000000') {
          this.data = data
          findSelectedMenu(data, this.defaultCheckedKeys)
        }
      },
      async onSubmit() {
        console.log(this.$refs.menuTree.getCheckedKeys())
        const data = {
          "roleId": this.roleId,
          "menuIdList": this.$refs.menuTree.getCheckedKeys()
        }
        const { code } = await allocateRoleMenus(data)
        if (code === '000000') {
          this.$message.success('保存成功')
          this.$router.push({ name: 'role' })
        }
      },
      reset() {
        this.$refs.menuTree.setCheckedKeys([])
      }
    },
  }
</script>

<style lang="scss" scoped>
  .button-container {
    display: flex;
    justify-content: center;
  }
</style>
